from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, create_refresh_token
from models import User, db
from utils.auth import bcrypt
from utils.sms import send_sms_code
import re
import redis

auth_bp = Blueprint('auth', __name__)
redis_client = redis.from_url(current_app.config['REDIS_URL'])

@auth_bp.route('/api/send_sms', methods=['POST'])
def send_sms():
    phone = request.json.get('phone')
    # 校验手机号格式
    if not re.match(r'^1[3-9]\d{9}$', phone):
        return jsonify(code=400, msg='手机号格式错误'), 400
    # 限流控制（1分钟1次）
    if redis_client.get(f'sms_limit:{phone}'):
        return jsonify(code=429, msg='操作过于频繁'), 429
    # 生成并存储验证码
    code = str(random.randint(100000, 999999))
    redis_client.setex(f'sms_code:{phone}', 300, code)
    redis_client.setex(f'sms_limit:{phone}', 60, '1')
    # 异步发送短信
    send_sms_code.delay(phone, code)
    return jsonify(code=200, msg='验证码已发送')

@auth_bp.route('/api/login/sms', methods=['POST'])
def login_with_sms():
    phone = request.json.get('phone')
    code = request.json.get('code')
    # 校验验证码
    stored_code = redis_client.get(f'sms_code:{phone}')
    if not stored_code or stored_code.decode() != code:
        return jsonify(code=400, msg='验证码错误'), 400
    # 自动注册逻辑
    user = User.query.filter_by(phone=phone).first()
    if not user:
        user = User(phone=phone)
        db.session.add(user)
        db.session.commit()
    # 生成JWT
    access_token = create_access_token(identity=user.id)
    refresh_token = create_refresh_token(identity=user.id)
    return jsonify(
        code=200,
        data={'access_token': access_token, 'refresh_token': refresh_token}
    )